package com.jp.knowledge.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dmcc.image_preview.ImagePreviewActivity;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.HeadItemAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.DocBean;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.InfoData;
import com.jp.knowledge.model.TopicInfo;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.KeyBordLayoutListener;
import com.jp.knowledge.view.TalkBottomView;
import com.jp.knowledge.webUtil.JavaScriptInterface;
import com.jp.knowledge.webUtil.X5WebView;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jiayen
 *         详情信息
 */
public class InfoDataDetail extends SlidingActivity implements ResultSubscriber.OnResultListener, View.OnClickListener {

    private static final String TAG = "InfoDataDetail";
    private final int DETAIL_CODE = 0x000001;//详情页
    private final int COLLECT_CODE = 0x000002;//收藏
    private final int CANCLE_COLLECT_CODE = 0x000003;//取消收藏
    private final int ADD_COMMENT_CODE = 0x000004;//添加评论
    private final int GET_TOPIC_CODE = 0x000005;//获取话题数据
    private X5WebView webView;//加载webView

    private String id;//详情id用户请求数据
    private int type;//详情数据类型
    private String linkIcon;
    private String linkTitle;

    private HeadItemAdapter adapter;
    private TextView content;

    private InfoData info;
    private InputMethodManager inputManager;

    private TalkBottomView talkBottom;
    private String HOST_URL = "http://g.jp580.com/headlines#/headlines/content?";

    @ViewInject(R.id.progressBar1)
    private ProgressBar mPageLoadingProgressBar;

    @ViewInject(R.id.top_return)
    private ImageView returnView;

    @ViewInject(R.id.root_view)
    private RelativeLayout rootView;

    @ViewInject(R.id.shade_view)
    private View shadeView;

    @ViewInject(R.id.j_right_icon)
    private ImageView rightIcon;//所谓的竞一下按钮图标


    @ViewInject(R.id.detial_search_icon)
    private TextView deatilSearchIcon;



    private KeyBordLayoutListener keyBordLayoutListener;


    private FileCacheManager fileCacheManager;
    private String CACHE_PATH;


    /**本地广播 接收数据同步*/
    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadCast localBroadCast;

    private int detail_type=0;
    private JsonArray imgUrl;
    private List<String> imgPahts;

    @Override
    protected int getResourceId() {
        return R.layout.activity_info_data_detail;
    }


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
           String data  = msg.obj.toString();
            JsonObject obj = JsonUtil.getInstance().strToJson(data);
            String key = obj.get("key").getAsString();
            if(key!=null&&key.equals("data")){
                imgUrl = obj.get("param").getAsJsonArray();
                imgPahts = new Gson().fromJson(imgUrl, new TypeToken<List<String>>(){}.getType());
//                ToasUtil.toast(context,obj.get("param").getAsString());
            }else if(key!=null&&key.equals("click")){
                int index = obj.get("param").getAsInt();
//                ToasUtil.toast(context,index+"");
                showImags(index);
            }

        }
    };

    /**
     * 显示大图
     */
    private void showImags(int index) {
        ImagePreviewActivity.startActivity(mContext, index, (ArrayList<String>) imgPahts);
    }

    @Override
    protected void init() {
        talkBottom = (TalkBottomView) findViewById(R.id.talk_bottom);
        String param = getIntent().getStringExtra("param");
        if(param!=null){
           JsonObject json =  JsonUtil.getInstance().strToJson(param);
            detail_type= json.get("type").getAsInt();
            id= json.get("id").getAsString();
            if(detail_type==6){//文库进来详情
//                talkBottom.showReadDocBtn(this);
            }else{
                id = getIntent().getStringExtra("id");
            }
        }else{
            id = getIntent().getStringExtra("id");
        }

        type = getIntent().getIntExtra("type", 1);
        linkIcon = getIntent().getStringExtra("linkIcon");
        linkTitle = getIntent().getStringExtra("linkTitle");

        CACHE_PATH = getCacheDir() + "/info_detail_" + id + ".data";
        fileCacheManager = new FileCacheManager();

        initWebView();

        initRoatAnimation();

        content = (TextView) findViewById(R.id.content);


        talkBottom.setShadeView(shadeView);
        talkBottom.setInfoId(id);
        talkBottom.setType(type);
        talkBottom.setLinkIcon(linkIcon);
        talkBottom.setLinkTitle(linkTitle);

        returnView.setOnClickListener(this);

//        UmengTool.getSignature(context);
        keyBordLayoutListener = new KeyBordLayoutListener();
        keyBordLayoutListener.setRootView(talkBottom);
        keyBordLayoutListener.setListener(new KeyBordLayoutListener.KeyBordListener() {
            @Override
            public void onHideKeyboard() {
                L.e("onHideKeyboard");
                talkBottom.hideEdit();
                shadeView.setVisibility(View.GONE);
                talkBottom.clearEdit();
            }

            @Override
            public void onShowKeyboard() {
                L.e("onShowKeyboard");
                talkBottom.showEdit();
            }
        });
        talkBottom.getViewTreeObserver().addOnGlobalLayoutListener(keyBordLayoutListener);
        shadeView.setOnClickListener(this);

        getDetailData();

        //注册广播刷新数据
        registerBroadCast();
    }

    /**
     * 初始化旋转动画
     */
    private void initRoatAnimation() {
        Animation rotate = AnimationUtils.loadAnimation(mContext, R.anim.search_roat);//创建动画
        rotate.setInterpolator(new LinearInterpolator());//设置为线性旋转
        rotate.setFillAfter(true);//每次都取相反值，使得可以不恢复原位的旋转imageView.startAnimation(rotate);
        rotate.setRepeatCount(Integer.MAX_VALUE);
        deatilSearchIcon.setAnimation(rotate);
        rotate.start();
    }

    /**
     * 初始化webView
     */
    private void initWebView() {
        webView = (X5WebView) findViewById(R.id.web_content);
//        QbSdk.allowThirdPartyAppDownload(true);
        X5WebView.setSmallWebViewEnabled(true);// 开启webview窗口转移功能

        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                talkBottom.hideSoftAndEdit();
                return false;
            }
        });


        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                final int progress = newProgress;
                mPageLoadingProgressBar.setProgress(newProgress);
                if (mPageLoadingProgressBar != null && newProgress != 100) {
                    mPageLoadingProgressBar.setVisibility(View.VISIBLE);
                } else if (mPageLoadingProgressBar != null) {
                    mPageLoadingProgressBar.setVisibility(View.GONE);
                }
            }
        });
        WebSettings webSetting = webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(false);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(mHandler), "Android");
    }

    private void registerBroadCast(){
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(action.equals(LocalBroadCast.DETAIL_SC_BROAD)){//收藏广播
                    talkBottom.setScIcon();//改变标识
                }else if(action.equals(LocalBroadCast.ADD_TOPIC_BROAD)){//抢开话题广播
                    TopicInfo topic = intent.getParcelableExtra("topic");
                    info.setTopicInfo(topic);
                    if(topic!=null)
                    talkBottom.setEditHint("你可继续此话题!");
                    if(topic!=null)
                        talkBottom.setPlNum(topic.getCount());
                }
            }
        });
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.DETAIL_SC_BROAD);//收藏监听广播
        intentFilter.addAction(LocalBroadCast.ADD_TOPIC_BROAD);//添加话题广播
        localBroadcastManager.registerReceiver(localBroadCast,intentFilter);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            talkBottom.getViewTreeObserver().removeGlobalOnLayoutListener(keyBordLayoutListener);
        } else {
            talkBottom.getViewTreeObserver().removeOnGlobalLayoutListener(keyBordLayoutListener);
        }
        localBroadcastManager.unregisterReceiver(localBroadCast);
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 获取详情数据
     */
    private void getDetailData() {
        showBgLoadingDialog();
        httpGetData();
    }

    private void httpGetData() {
        JsonObject obj = new JsonObject();
        obj.addProperty("id", id);
        if(detail_type==6){
            obj.addProperty("type", detail_type);
        }else {
            obj.addProperty("type", type);
        }
        HttpHelper.getInstance(mContext).getInfoDataDetail(obj, DETAIL_CODE, this);
    }

    @Override
    public void onStart(int requestType) {
//        showLoading();
    }

    @Override
    public void onCompleted(int requestType) {
//        cancleLoading();
    }

    @Override
    public void onError(int requestType) {
//        cancleLoading();
        cancleBgLoadingDialog();
    }

    @Override
    public void onNext(IModel data, int requestType) {

        int code = data.getErrcode();
        switch (requestType) {
            case DETAIL_CODE://代表详情数据获取成功
                if (code == 0)
                    handDetailInfo(data);
                else
                    ToasUtil.toast(mContext, "请求有误");
                cancleBgLoadingDialog();
                break;
            case  GET_TOPIC_CODE:
                handTopic(data);
                break;
            default:
                break;
        }
    }

    /**
     * 处理话题数据
     * @param data
     */
    private void handTopic(IModel data) {
       if(data.getErrcode()!=0){
//            hidePlnum();
           talkBottom.setPlNum(0);
        //获取话题数据失败
           ToasUtil.toast(mContext,"获取话题数据失败!");
        }
        TopicInfo topic = data.getEntity(TopicInfo.class);
        if(topic!=null&&!TextUtils.isEmpty(topic.getTopicId())){
            talkBottom.setEditHint("你可继续此话题!");
            talkBottom.setPlNum(topic.getCount());
//            showPlnum();
        }else{
            talkBottom.setPlNum(0);
        }
        L.d("topicInfo======" + topic);
        info.setTopicInfo(topic);
        setDetailData(info);
    }

//    /**
//     * 隐藏评论数量
//     */
//    private void hidePlnum(){
//        plNum.setVisibility(View.GONE);
//    }
//
//    /**
//     * 显示评论数量
//     */
//    private void showPlnum(int num){
//        plNum.setText(num);
//        plNum.setVisibility(View.VISIBLE);
//    }

    /**
     * 处理详情数据
     *
     * @param data
     */
    private void handDetailInfo(IModel data) {


//        LinkedTreeMap<String, Object> map = (LinkedTreeMap<String, Object>) data.getData();

        info = data.getEntity(InfoData.class);//JsonUtil.getInstance().mapToObject(map, InfoData.class);
//        saveCache(info);//添加至缓存

        if((info.getUrl() == null || info.getUrl().trim().length() == 0)
        && (info.getHtml() == null || info.getHtml().trim().length() == 0)
        && info.getQiniuUrl() != null && info.getQiniuUrl().trim().length() > 0){
            opendDoc();
            finish();
        }

        if(info!=null&&!TextUtils.isEmpty(info.getQiniuUrl())){
            talkBottom.showReadDocBtn(this);
        }

        //获取详情数据成功后  获取话题数据
        JsonObject param = new JsonObject();
        param.addProperty("id",id);
        param.addProperty("type",type);
        HttpHelper.getInstance(mContext).headlinesTopicDetails(param,GET_TOPIC_CODE,this);
    }

    /**
     * 设置详情的值
     * @param info
     */
    private void setDetailData(InfoData info) {
        talkBottom.setInfo(info);
        final String html = info.getHtml();
        if (html == null || html.trim().length() < 10 || html.equals("")) {
            webView.loadUrl(info.getUrl());
        } else {
            webView.loadUrl("file:///android_asset/htmlTemplate.html");
            webView.setUrlHandler(new X5WebView.UrlHandler() {
                @Override
                public void handUrl(String url) {
                    webView.loadUrl("javascript:showHtml('" + html + "')");
//                    cancleLoading();
                }

                @Override
                public void handError(WebView webView, int i, String s, String s1) {
//                    ToasUtil.toast(context,"错误显示====i="+i+"=====s="+s+"======s1="+s1);
                }
            });
        }
    }

    /**
     * 保存缓存
     *
     * @param info
     */
    private void saveCache(final InfoData info) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //此处info是实现Parcelable所以不好保存 则转出json字符串来保存
                String json = JsonUtil.getInstance().objToJson(info);
                fileCacheManager.wirteObject(json, CACHE_PATH);
            }
        }).start();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.web_content://点击页面隐藏编辑框
                talkBottom.hideSoftAndEdit();
                break;
            case R.id.top_return://返回
                this.finish();
            case R.id.shade_view://返回
                talkBottom.hideSoftAndEdit();
                break;
            case R.id.read_doc_btn://打开文档
                opendDoc();

                break;
            default:
                break;
        }
    }

    /**
     * 打开文档
     */
    private void opendDoc() {
        Intent intent = new Intent(mContext,ReadDocActivity.class);
        if(info!=null){
            DocBean doc = new DocBean();
            doc.setBaiduCode(info.getBaiduCode());
            doc.setHost(info.getHost());
            doc.setToken(info.getToken());
            doc.setFormat(info.getFormat());
            doc.setPdfUrl(info.getQiniuUrl());
            intent.putExtra("doc",doc);

            int pageCout = info.getPageCout();
            pageCout = 150;
            String pdfUrl = info.getQiniuUrl();
            pdfUrl = pdfUrl.substring(0, pdfUrl.length()-3);
            ArrayList<String> qiniuUrls = new ArrayList<>();
            for(int i = 1; i <= pageCout; i++){
                qiniuUrls.add(pdfUrl + i + ".jpg");
            }
            OpenDocActivity.startActivity(this, 0, qiniuUrls, doc);
            return;
        }
        startActivity(intent);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if(talkBottom.)
        return super.onKeyDown(keyCode, event);
    }
}